<template>
  <div class="alloc-menu">
    <el-card>
      <el-tree
        ref="tree"
        node-key="id"
        :data="menu"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        :default-checked-keys="checkKeys"
        @node-click="handleNodeClick"
      ></el-tree>
      <div style="margin-top:30px;text-align:center">
        <el-button
          type="primary"
          @click="saveMenu"
        >保存</el-button>
        <el-button
          @click="onReset"
        >清空</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getMenuNodeList, allocateMenu, getRoleMenu } from '@/services/role'
export default {
  name: 'AllocMenu',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  created () {
    this.loadAllocMenu()
    this.loadRoleMenu()
  },
  data () {
    return {
      menu: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      checkKeys: []
    }
  },
  methods: {
    handleNodeClick (data) {
      // console.log(data)
    },
    // 获取所有菜单项
    async loadAllocMenu () {
      const { data } = await getMenuNodeList()
      if (data.code === '000000') {
        this.menu = data.data
      }
      // console.log(data)
    },
    // 保存分配的菜单
    async saveMenu () {
      const { data } = await allocateMenu({
        roleId: this.roleId,
        menuIdList: this.$refs.tree.getCheckedKeys()
      })
      if (data.code === '000000') {
        console.log(this.$refs.tree.getCheckedKeys())
        this.$message.success('角色分配菜单成功！')
        this.$router.push({
          name: 'role'
        })
      }
    },
    getcheckedKeys (menus) {
      // 遍历数组（将所有存在子节点的 node 排除）
      menus.forEach(menu => {
        // 未选中
        if (!menu.selected) {
          return
        }
        // 检测是否存在子节点
        if (menu.subMenuList) {
          return this.getcheckedKeys(menu.subMenuList)
        }
        // 选中叶子节点，并储存ID
        // this.checkKeys.push(menu.id)
        // 异步频繁的修改数组，页面渲染有问题
        this.checkKeys = [...this.checkKeys, menu.id]
        console.log('checkKeys', this.checkKeys)
      })
    },
    async loadRoleMenu () {
      const { data } = await getRoleMenu(this.roleId)
      if (data.code === '000000') {
        this.getcheckedKeys(data.data)
      }
    },
    // 清空菜单
    onReset () {
      this.$refs.tree.setCheckedKeys([])
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
